<?php

namespace Wantuch\MailerBundle\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpFoundation\JsonResponse;
use Wantuch\MailerBundle\Entity\Company;
use Wantuch\MailerBundle\Form\Type\CompanyType;
use Wantuch\MailerBundle\Entity\Campaign;
use Wantuch\MailerBundle\Form\Type\CampaignType;
use Wantuch\MailerBundle\Entity\Subscriber;
use Wantuch\MailerBundle\Form\Type\SubscriberType;
use Wantuch\MailerBundle\Entity\Message;
use Wantuch\MailerBundle\Form\Type\MessageType;

use Hip\MandrillBundle\Message as MandrillMessage;
use Hip\MandrillBundle\Dispatcher;

class MainController extends Controller
{
    public function indexAction(Request $request)
    {
    $response = $this->render('WantuchMailerBundle:Main:index.html.twig');
    $response->setETag(md5($response->getContent()));
    $response->setPublic(); // make sure the response is public/cacheable
    $response->isNotModified($request);

    return $response;
    }
    
    public function indexRedirectAction(){
        return $this->redirect($this->generateUrl('wantuch_homepage_admin'));
    }
    
    public function createExampleCompanyAction()
    {
        $product = new Company();
        $product->setName("Przyklaodowa");
        $product->setOwner("Przyklaodwy");
        $product->setShortName("Prz");

        $em = $this->getDoctrine()->getManager();
        $em->persist($product);
        $em->flush();

        return new Response('Created product id '.$product->getId());
    }
    
    public function getAllCompaniesAction(Request $request){
        $repository = $this->getDoctrine()->getRepository('WantuchMailerBundle:Company');
        $companies = $repository->findAll();
        
        $response = $this->render('WantuchMailerBundle:Main:companies.html.twig', array('companies' => $companies));
        $response->setETag(md5($response->getContent()));
        $response->setPublic(); // make sure the response is public/cacheable
        $response->isNotModified($request);

    return $response;
        //return $this->render('WantuchMailerBundle:Main:companies.html.twig', array('companies' => $companies));
    }
    

    
    public function getAllSubscribersAction(Request $request){
        $repository = $this->getDoctrine()->getRepository('WantuchMailerBundle:Subscriber');
        $subscribers = $repository->findAll();
        
        $response = $this->render('WantuchMailerBundle:Main:subscribers.html.twig', array('subscribers' => $subscribers));
        $response->setETag(md5($response->getContent()));
        $response->setPublic();
        $response->isNotModified($request);

    return $response;
    }
    
    public function getAllSubscribersFromCampaignAction(Request $request, $campaign_id){
        $em = $this->getDoctrine()->getEntityManager();
        $campaign = $em->getRepository('WantuchMailerBundle:Campaign')->find($campaign_id);
        
        $response = $this->render('WantuchMailerBundle:Main:campaignSubscribers.html.twig', array('campaign' => $campaign));
        $response->setETag(md5($response->getContent()));
        $response->setPublic();
        $response->isNotModified($request);

    return $response;
    }
    
    public function messagesCampaignAction(Request $request, $campaign_id){
        $em = $this->getDoctrine()->getEntityManager();
        $campaign = $em->getRepository('WantuchMailerBundle:Campaign')->find($campaign_id);
        
        $response = $this->render('WantuchMailerBundle:Main:campaignMessages.html.twig', array('campaign' => $campaign));
        $response->setETag(md5($response->getContent()));
        $response->setPublic();
        $response->isNotModified($request);

    return $response;
    }
    
    public function getAllCampaignsAction(Request $request){
        $repository = $this->getDoctrine()->getRepository('WantuchMailerBundle:Campaign');
        $campaigns = $repository->findAll();
        
        $response = $this->render('WantuchMailerBundle:Main:campaigns.html.twig', array('campaigns' => $campaigns));
        $response->setETag(md5($response->getContent()));
        $response->setPublic();
        $response->isNotModified($request);

    return $response;
    }
    
    
    
    public function addCompanyAction(Request $request)
    {
        $company = new Company();
        $form = $this->createForm(new CompanyType(), $company);
        
        $form->handleRequest($request);

        if ($form->isValid()) {
            // perform some action, such as saving the task to the database
            $em = $this->getDoctrine()->getManager();
            $em->persist($company);
            $em->flush();    
            
            return $this->redirect($this->generateUrl('wantuch_homepage_admin'));
        }
        
        return $this->render('WantuchMailerBundle:Main/Form:addCompany.html.twig', array('form' => $form->createView()));
    }
    
    public function unsubscribeAction(Request $request, $subscriber_id, $subscriber_token)
    {
        $em = $this->getDoctrine()->getEntityManager();
        $subscriber = $em->getRepository('WantuchMailerBundle:Subscriber')->find($subscriber_id);
        if($subscriber && $subscriber->getToken()==$subscriber_token){
            $subscriber->setActive("N");
            $subscriber->setUpdatedAt(new \DateTime());
            $em->persist($subscriber);
            $em->flush();
            return $this->render('WantuchMailerBundle:Main:unsubscribe.html.twig', array('subscriber'=>$subscriber));
        }else{
            return new Response('<pre>Nie zgadza się token! Nie oszukuj.</pre>');
        }
        
        
    }
    
        public function addCampaignAction(Request $request)
    {
        $campaign = new Campaign();
        $form = $this->createForm(new CampaignType(), $campaign);
        
        $form->handleRequest($request);

        if ($form->isValid()) {
            // perform some action, such as saving the task to the database
            $em = $this->getDoctrine()->getManager();
            $em->persist($campaign);
            $em->flush();    
            
            return $this->redirect($this->generateUrl('wantuch_homepage_admin'));
        }
        
        return $this->render('WantuchMailerBundle:Main/Form:addCampaign.html.twig', array('form' => $form->createView()));
    }
    
    public function addSubscriberAction(Request $request)
    {
        $subscriber = new Subscriber();
        $form = $this->createForm(new SubscriberType(), $subscriber);
        
        $form->handleRequest($request);

        if ($form->isValid()) {
            // perform some action, such as saving the task to the database
            $em = $this->getDoctrine()->getManager();
            $token=md5(date('l jS \of F Y h:i:s A').$subscriber->getEmail());
            $subscriber->setToken($token);
            $em->persist($subscriber);
            $em->flush();    
            
            return $this->redirect($this->generateUrl('wantuch_homepage_admin'));
        }
        
        return $this->render('WantuchMailerBundle:Main/Form:addSubscriber.html.twig', array('form' => $form->createView()));
    }
    
    public function addSubscriberCampaignAction(Request $request, $campaign_id)
    {
        $em = $this->getDoctrine()->getEntityManager();
        $campaign = $em->getRepository('WantuchMailerBundle:Campaign')->find($campaign_id);
        
        $subscriber = new Subscriber();
        $form = $this->createForm(new SubscriberType(), $subscriber);
        
        $form->handleRequest($request);

        if ($form->isValid()) {
            // perform some action, such as saving the task to the database
            $em = $this->getDoctrine()->getManager();
            $token=md5(date('l jS \of F Y h:i:s A').$subscriber->getEmail());
            $subscriber->setToken($token);
            $subscriber->setCampaign($campaign);
            $em->persist($subscriber);
            $em->flush();    
            
            return $this->redirect($this->generateUrl('wantuch_get_all_subscribers_from_campaign',array('campaign_id'=>$campaign->getId())));
        }
        
        return $this->render('WantuchMailerBundle:Main/Form:addSubscriberCampaign.html.twig', array('form' => $form->createView(),'campaign'=>$campaign));
    }
    
    public function editSubscriberAction(Request $request, $id)
    {
    
    
        $em = $this->getDoctrine()->getEntityManager();
        $subscriber = $em->getRepository('WantuchMailerBundle:Subscriber')->find($id);
        $form = $this->createForm(new SubscriberType(), $subscriber);
        
        $form->handleRequest($request);

        if ($form->isValid()) {
            // perform some action, such as saving the task to the database
            $em = $this->getDoctrine()->getManager();
            $em->persist($subscriber);
            $em->flush();    
            
            return $this->redirect($this->generateUrl('wantuch_homepage_admin'));
        }
        
        return $this->render('WantuchMailerBundle:Main/Form:editSubscriber.html.twig', array('form' => $form->createView()));
    }
    
    public function sendMessageCampaignAction(Request $request, $campaign_id)
    {
        $em = $this->getDoctrine()->getManager();
        $campaign = $em->getRepository('WantuchMailerBundle:Campaign')->find($campaign_id);
       
        $message = new Message();
        $message->setSender($campaign->getDefaultSender());

        $form = $this->createFormBuilder($message)
            ->add('sender','text',array('label'=>'Nadawca'))
            ->add('title','text',array('label'=>'Tytuł'))
            ->add('content')
            ->add('csvFile', 'file', array('required'=>false,'mapped'=>false,'label'=>"Wczytaj dodatkowo z pliku CSV"))
            ->add('additionalReceivers', 'textarea', array('required'=>false,'mapped' => false,'label'=>'Dodatkowi odbiorcy po przecinku (zostaną dodani do bazy)'))
            ->add('attachments', 'file', array('label'=>'Załączniki', 'multiple'=>true,'required'=>false))
            ->add('save', 'submit', array('label' => 'Wyślij wiadomość'))
            ->getForm();

        $form->handleRequest($request);

        if ($form->isValid()) {
            $csvFile=array();
            if($form["csvFile"]->getData()!=NULL){
               $csvFile = array_map('str_getcsv', file($form["csvFile"]->getData()));
            
                foreach($csvFile as $singleLine){
                    $line=explode(';',$singleLine[0]);

                    $subscriber = new Subscriber();
                    $subscriber->setEmail($line[2]);
                    $subscriber->setName($line[0]);
                    $subscriber->setSurname($line[1]);
                    $token=md5(date('l jS \of F Y h:i:s A').$subscriber->getEmail());
                    $subscriber->setToken($token);
                    $subscriber->setCampaign($campaign);
                    $subscriber->setActive("T");
                    $subscriber->setSource("CSV");
                    $subscriber->setCreatedAt(new \DateTime());
                    $em->persist($subscriber);

                } 
            }
            
            //return new Response('<pre>' . print_r($lines, true) . '</pre>');
            $pieces=array();
            if($form["additionalReceivers"]->getData()!=""){
                $additionalEmails  = $form["additionalReceivers"]->getData();
                $pieces = explode(",", $additionalEmails);

                foreach($pieces as $singleEmail){
                    if($singleEmail!=""){
                        $subscriber = new Subscriber();
                        $subscriber->setEmail($singleEmail);
                        $token=md5(date('l jS \of F Y h:i:s A').$subscriber->getEmail());
                        $subscriber->setToken($token);
                        $subscriber->setCampaign($campaign);
                        $subscriber->setActive("T");
                        $subscriber->setSource("By hand on send");
                        $subscriber->setCreatedAt(new \DateTime());
                        $em->persist($subscriber); 
                    }   
                }
            }
            
            $message->setCampaign($campaign);
            $message->setIsSent("T");
            $message->setSendDate(new \DateTime());
            $message->setAttachments("");
            $message->setCreatedAt(new \DateTime());
            $em->persist($message);
                
            $em->flush();
            
            $server_path="http://mailer.timedo.civ.pl";
            
            $dispatcher = $this->get('hip_mandrill.dispatcher');
            
            foreach($campaign->getSubscribers() as $singleSubscriber){
                $unsubscribe_link= $server_path.$this->generateUrl('wantuch_mailer_unsubscribe', array('subscriber_id' => $singleSubscriber->getId(),'subscriber_token' => $singleSubscriber->getToken()));
                $messageForSend = new MandrillMessage();
                $messageForSend
                ->setFromEmail($message->getSender())
                ->setFromName($message->getCampaign()->getCompany()->getOwner())
                ->addTo('wojtekwantuch+test1@gmail.com')
                ->setSubject($message->getTitle())
                ->setHtml($message->getContent()."<br /><br />Aby wypisać się z subskrybcji kliknij ten link: ".$unsubscribe_link);
                
                foreach($form["attachments"]->getData() as $attach){
                    if($attach!=NULL){
                        $attachContent=file_get_contents($attach->getPathName());
                        $attachName=$attach->getClientOriginalName();
                        $attachBase64=base64_encode($attachContent);
                        $attachType=$attach->getMimeType();
                        $messageForSend->addAttachment($attachType, $attachName, $attachBase64);
                    }
                }
                $a=$dispatcher->send($messageForSend);    
            }

            
            
            return $this->render('WantuchMailerBundle:Main:sendMessageSummary.html.twig', array('csvFile'=>$csvFile,'additional'=>$pieces,'campaign'=>$campaign,'message'=>$message,'subscribers'=>$campaign->getSubscribers()));

        }
        return $this->render('WantuchMailerBundle:Main/Form:sendMessageCampaign.html.twig', array('form' => $form->createView(),'campaign'=>$campaign));

        
    }
    
    public function mailTestAction()
    {
        $dispatcher = $this->get('hip_mandrill.dispatcher');

        $message = new MandrillMessage();

        $message
            ->setFromEmail('wwwwww1@wwwwww.com')
            ->setFromName('Wojtek z Przysiek 1 ')
            ->addTo('wojtekwantuch+test1@gmail.com')
            ->setSubject('Mądry tytuł 1')
            ->setHtml('<html><body><h1>A to dopierdo header</h1></body></html>');
            
        $dispatcher->send($message);
        
        $message
            ->setFromEmail('wwwwww2@wwwwww.com')
            ->setFromName('Wojtek z Przysiek2')
            ->addTo('wojtekwantuch+test2@gmail.com')
            ->setSubject('Mądry tytuł 2')
            ->setHtml('<html><body><h1>A to dopierdo header</h1></body></html>');
            
       
        $result = $dispatcher->send($message);

        return new Response('<pre>' . print_r($result, true) . '</pre>');

    }
    
    public function ajaxDetailsCampaignAction(Request $request)    
    {
        if ($request->isXMLHttpRequest()) {
            $identifier=$request->get("id");
            $em = $this->getDoctrine()->getManager();
            $object = $em->getRepository('WantuchMailerBundle:Campaign')->find($identifier);
            $view = $this->renderView('WantuchMailerBundle:Main/Ajax:detailsCampaign.html.twig',array('campaign'=>$object));
            return new JsonResponse(array('data' => $view));
        }

        return new Response('This is not ajax!', 400);
    }
    public function ajaxDetailsSubscriberAction(Request $request)    
    {
        if ($request->isXMLHttpRequest()) {
            $identifier=$request->get("id");
            $em = $this->getDoctrine()->getManager();
            $object = $em->getRepository('WantuchMailerBundle:Subscriber')->find($identifier);
            $view = $this->renderView('WantuchMailerBundle:Main/Ajax:detailsSubscriber.html.twig',array('subscriber'=>$object));
            return new JsonResponse(array('data' => $view));
        }

        return new Response('This is not ajax!', 400);
    }
    
    public function ajaxDetailsCompanyAction(Request $request)    
    {
        if ($request->isXMLHttpRequest()) {
            $identifier=$request->get("id");
            $em = $this->getDoctrine()->getManager();
            $object = $em->getRepository('WantuchMailerBundle:Company')->find($identifier);
            $view = $this->renderView('WantuchMailerBundle:Main/Ajax:detailsCompany.html.twig',array('company'=>$object));
            return new JsonResponse(array('data' => $view));
        }

        return new Response('This is not ajax!', 400);
    }
    
    public function ajaxDetailsMessageAction(Request $request)    
    {
        if ($request->isXMLHttpRequest()) {
            $identifier=$request->get("id");
            $em = $this->getDoctrine()->getManager();
            $object = $em->getRepository('WantuchMailerBundle:Message')->find($identifier);
            $view = $this->renderView('WantuchMailerBundle:Main/Ajax:detailsMessage.html.twig',array('message'=>$object));
            return new JsonResponse(array('data' => $view));
        }

        return new Response('This is not ajax!', 400);
    }
}
